from snowboy import snowboydecoder
import sys
import signal
import os
from robot import Player, constants
from robot.Conversation import Conversation
import base64
import requests
import fire
import hashlib
from robot import TTS, constants, utils
from aip import AipSpeech


class Xiaohei(object):
    _profiling = False

    def init(self):
        self.detector = None
        self._interrupted = False

        self._conversation = Conversation(self._profiling)
        self._conversation.say('智能货柜为您服务', True)

    def _signal_handler(self, signal, frame):
        self._interrupted = True

    def _interrupt_callback(self):
        return self._interrupted

    def _detected_callback(self):
        def start_record():
            print('开始录音')
            self._conversation.isRecording = True

        if self._conversation.isRecording:
            print('正在录音中，跳过')
            return

        self._conversation.interrupt()
        Player.play('snowboy/resources/我在.mp3',
                    onCompleted=start_record, wait=True)

    def run(self):
        self.init()

        # capture SIGINT signal, e.g., Ctrl+C
        signal.signal(signal.SIGINT, self._signal_handler)

        try:
            self.initDetector()
        except AttributeError:
            print('初始化离线唤醒功能失败')
            pass

    def initDetector(self):
        if self.detector is not None:
            self.detector.terminate()

        model = constants.getHotwordModel('小白.pmdl')

        self.detector = snowboydecoder.HotwordDetector(
            model, sensitivity=0.5)

        # main loop
        try:
            callbacks = self._detected_callback
            self.detector.start(detected_callback=callbacks,
                                audio_recorder_callback=self._conversation.converse,
                                interrupt_check=self._interrupt_callback,
                                silent_count_threshold=15,
                                recording_timeout=5*4,
                                sleep_time=0.03)
            self.detector.terminate()
        except Exception as e:
            print('离线唤醒机制初始化失败：{}'.format(e))

    def md5(self, password):
        """
        计算字符串的 md5 值
        """
        return hashlib.md5(str(password).encode('utf-8')).hexdigest()

    def train(self, w1, w2, w3, m):
        '''
        传入三个wav文件，生成snowboy的.pmdl模型
        '''
        ############# MODIFY THE FOLLOWING #############
        token = "2d83c46121ccedb88803646e0792c1641138a352"
        hotword_name = "xiaobai"
        language = "zh"
        age_group = "20_29"
        gender = "M"
        microphone = "macbook microphone"
        ############### END OF MODIFY ##################

        def get_wave(fname):
            with open(fname, 'rb') as infile:
                return base64.b64encode(infile.read()).decode('utf-8')
        url = 'https://snowboy.kitt.ai/api/v1/train/'
        data = {
            "name": hotword_name,
            "language": language,
            "token": token,
            "voice_samples": [
                {"wave": get_wave(w1)},
                {"wave": get_wave(w2)},
                {"wave": get_wave(w3)}
            ]
        }
        response = requests.post(url, json=data)
        if response.ok:
            with open(m, "wb") as outfile:
                outfile.write(response.content)
            return 'Snowboy模型已保存至{}'.format(m)
        else:
            return "Snowboy模型生成失败，原因:{}".format(response.text)

if __name__ == '__main__':

    if len(sys.argv) == 1:
        xiaohei = Xiaohei()
        xiaohei.run()
    else:
        fire.Fire(Xiaohei)
